<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  

  
  <title>JavaScript Template Engine | 在路上</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="设计目的减少现有代码中的字符串拼接操作，增强代码的可维护性。 实现代码123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354/* * @description An Easy Template in JavaScript, it is designed t">
<meta name="keywords" content="JavaScript">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript Template Engine">
<meta property="og:url" content="http://yoursite.com/2012/02/06/JavaScript-Template-Engine/index.html">
<meta property="og:site_name" content="在路上">
<meta property="og:description" content="设计目的减少现有代码中的字符串拼接操作，增强代码的可维护性。 实现代码123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354/* * @description An Easy Template in JavaScript, it is designed t">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2018-03-26T11:35:06.676Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JavaScript Template Engine">
<meta name="twitter:description" content="设计目的减少现有代码中的字符串拼接操作，增强代码的可维护性。 实现代码123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354/* * @description An Easy Template in JavaScript, it is designed t">
  
    <link rel="alternate" href="/atom.xml" title="在路上" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link rel="stylesheet" href="/css/style.css">
</head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">在路上</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">一位崇尚价值投资的 Web 开发者</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS Feed"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="Search"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="http://yoursite.com"></form>
      </div>
    </div>
  </div>
</header>
      <div class="outer">
        <section id="main"><article id="post-JavaScript-Template-Engine" class="article article-type-post" itemscope itemprop="blogPost">
  <div class="article-meta">
    <a href="/2012/02/06/JavaScript-Template-Engine/" class="article-date">
  <time datetime="2012-02-05T16:00:00.000Z" itemprop="datePublished">2012-02-06</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      JavaScript Template Engine
    </h1>
  

      </header>
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="设计目的"><a href="#设计目的" class="headerlink" title="设计目的"></a>设计目的</h2><p>减少现有代码中的字符串拼接操作，增强代码的可维护性。</p>
<h2 id="实现代码"><a href="#实现代码" class="headerlink" title="实现代码"></a>实现代码</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * @description An Easy Template in JavaScript, it is designed to reduce the string concatention work,</span></span><br><span class="line"><span class="comment"> * to make the gigantic code more readable and maintainable.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Template</span>(<span class="params">tmpl,source</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//add all template tasks to this array</span></span><br><span class="line">    <span class="keyword">this</span>.task = [];</span><br><span class="line">    <span class="keyword">if</span>(tmpl)</span><br><span class="line">        <span class="keyword">this</span>.task.push([tmpl,source]);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * @description core function,hanlde two cases: typeof dataSource is either object or array</span></span><br><span class="line"><span class="comment"> *  when the type of dataSource is array,you'd better confirm that the fields in every object is the same.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">Template.format = <span class="function"><span class="keyword">function</span>(<span class="params">template,dataSource</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//default variable flags</span></span><br><span class="line">    <span class="keyword">var</span> start = <span class="string">'&#123;'</span>, end = <span class="string">'&#125;'</span>;</span><br><span class="line">    <span class="keyword">if</span>(dataSource &amp;&amp; dataSource.slice &amp;&amp; dataSource.length)&#123;</span><br><span class="line">        <span class="keyword">var</span> retStr = [], formatted, len = dataSource.length, regMap = &#123;&#125;;</span><br><span class="line">        <span class="comment">//restore the RegExp,avoid to construct them repeatedly.</span></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> regKey <span class="keyword">in</span> dataSource[<span class="number">0</span>])&#123;</span><br><span class="line">            regMap[regKey] = <span class="keyword">new</span> <span class="built_in">RegExp</span>(start + regKey + end,<span class="string">'g'</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> index <span class="keyword">in</span> dataSource)&#123;</span><br><span class="line">            formatted = template;</span><br><span class="line">            <span class="keyword">for</span>(<span class="keyword">var</span> key <span class="keyword">in</span> dataSource[index])&#123;</span><br><span class="line">                formatted = formatted.replace(regMap[key],<span class="built_in">String</span>(dataSource[index][key]));</span><br><span class="line">            &#125;</span><br><span class="line">            retStr.push(formatted);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> retStr.join(<span class="string">''</span>);</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">var</span> key <span class="keyword">in</span> dataSource)&#123;</span><br><span class="line">            template = template.replace(<span class="keyword">new</span> <span class="built_in">RegExp</span>(start + key + end,<span class="string">'g'</span>),<span class="built_in">String</span>(dataSource[index][key]));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> template;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">Template.prototype.add = <span class="function"><span class="keyword">function</span>(<span class="params">tmpl,source</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//add one template task</span></span><br><span class="line">    <span class="keyword">this</span>.task.push([tmpl,source]);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * @description handle all tasks,and return the final string.</span></span><br><span class="line"><span class="comment"> *  when this method is invoked,you can reuse the instance.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">Template.prototype.end = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> retStr = [];</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">var</span> index <span class="keyword">in</span> <span class="keyword">this</span>.task)&#123;</span><br><span class="line">        retStr.push(Template.format(<span class="keyword">this</span>.task[index][<span class="number">0</span>],<span class="keyword">this</span>.task[index][<span class="number">1</span>]));    </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">this</span>.task.length = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">return</span> retStr.join(<span class="string">''</span>);</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>##使用方法</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!doctype html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"jTemp.js"</span>&gt;</span><span class="undefined"></span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">ul</span> <span class="attr">id</span>=<span class="string">"MenuItems"</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">li</span> <span class="attr">class</span>=<span class="string">"nav"</span>&gt;</span><span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"&#123;href&#125;"</span>&gt;</span>&#123;text&#125;<span class="tag">&lt;/<span class="name">a</span>&gt;</span><span class="tag">&lt;/<span class="name">li</span>&gt;</span>                </span><br><span class="line">        <span class="tag">&lt;/<span class="name">ul</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">script</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> ul = <span class="built_in">document</span>.getElementById(<span class="string">'MenuItems'</span>);</span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> dataSource = [</span></span><br><span class="line"><span class="javascript">                &#123;<span class="attr">text</span>:<span class="string">'首页'</span>,<span class="attr">href</span>:<span class="string">'http://www.oschina.net/'</span>&#125;,</span></span><br><span class="line"><span class="javascript">                &#123;<span class="attr">text</span>:<span class="string">'开源软件'</span>,<span class="attr">href</span>:<span class="string">'http://www.oschina.net/'</span>&#125;,</span></span><br><span class="line"><span class="javascript">                &#123;<span class="attr">text</span>:<span class="string">'讨论区'</span>,<span class="attr">href</span>:<span class="string">'http://www.oschina.net/'</span>&#125;,</span></span><br><span class="line"><span class="javascript">                &#123;<span class="attr">text</span>:<span class="string">'代码分享'</span>,<span class="attr">href</span>:<span class="string">'http://www.oschina.net/'</span>&#125;,</span></span><br><span class="line"><span class="javascript">                &#123;<span class="attr">text</span>:<span class="string">'资讯'</span>,<span class="attr">href</span>:<span class="string">'http://www.oschina.net/'</span>&#125;,</span></span><br><span class="line"><span class="javascript">                &#123;<span class="attr">text</span>:<span class="string">'博客'</span>,<span class="attr">href</span>:<span class="string">'http://www.oschina.net/'</span>&#125;,</span></span><br><span class="line"><span class="javascript">                &#123;<span class="attr">text</span>:<span class="string">'Android'</span>,<span class="attr">href</span>:<span class="string">'http://www.oschina.net/'</span>&#125;</span></span><br><span class="line"><span class="undefined">            ];</span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> tmpl = <span class="keyword">new</span> Template(ul.innerHTML,dataSource);</span></span><br><span class="line"><span class="undefined">            ul.innerHTML = tmpl.end();</span></span><br><span class="line"><span class="undefined">        </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="额外说明"><a href="#额外说明" class="headerlink" title="额外说明"></a>额外说明</h2><p>上面的例子更加偏向于一个穷人版的<strong>模板引擎</strong>（变量替换），如果这是你需要更加强大的例子，不妨看看 <code>jQuery</code> 的作者John Resig在几年前的 <a href="http://ejohn.org/blog/javascript-micro-templating/" target="_blank" rel="noopener">作品</a>。</p>
<p>不过模板引擎的发展在JavaScript圈子里面可谓日新月异，比较出名的有：</p>
<blockquote>
<ul>
<li>mustache</li>
<li>handlerbars</li>
<li>ejs</li>
<li>artTemplate (国产)</li>
</ul>
</blockquote>

      
    </div>
    <footer class="article-footer">
      <a data-url="http://yoursite.com/2012/02/06/JavaScript-Template-Engine/" data-id="cjf865uf400058wp1bbzhbw31" class="article-share-link">Share</a>
      
      
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/JavaScript/">JavaScript</a></li></ul>

    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2012/03/18/AOP-in-JavaScript/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          AOP in JavaScript
        
      </div>
    </a>
  
  
    <a href="/2011/10/22/JSONP-Memory-Leak/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">JSONP Memory Leak</div>
    </a>
  
</nav>

  
</article>

</section>
        
          <aside id="sidebar">
  
    

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签</h3>
    <div class="widget">
      <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript/">JavaScript</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript-解析器/">JavaScript,解析器</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/React/">React</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Redux/">Redux</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/SlimerJS/">SlimerJS</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/代码管理/">代码管理</a></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/持续集成/">持续集成</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">标签云</h3>
    <div class="widget tagcloud">
      <a href="/tags/JavaScript/" style="font-size: 20px;">JavaScript</a> <a href="/tags/JavaScript-解析器/" style="font-size: 10px;">JavaScript,解析器</a> <a href="/tags/React/" style="font-size: 16.67px;">React</a> <a href="/tags/Redux/" style="font-size: 10px;">Redux</a> <a href="/tags/SlimerJS/" style="font-size: 10px;">SlimerJS</a> <a href="/tags/代码管理/" style="font-size: 10px;">代码管理</a> <a href="/tags/持续集成/" style="font-size: 13.33px;">持续集成</a>
    </div>
  </div>

  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/09/">九月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/07/">七月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/06/">六月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/03/">三月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2016/02/">二月 2016</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/12/">十二月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/06/">六月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/05/">五月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2015/04/">四月 2015</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/07/">七月 2014</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2014/06/">六月 2014</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/11/">十一月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/10/">十月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/07/">七月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/03/">三月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2012/02/">二月 2012</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2011/10/">十月 2011</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2010/01/">一月 2010</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/1970/01/">一月 1970</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2016/09/09/space/">空格</a>
          </li>
        
          <li>
            <a href="/2016/07/17/parser/">JavaScript Parser资源总结</a>
          </li>
        
          <li>
            <a href="/2016/06/29/slimerjs/">使用SlimerJS将网页输出为PDF</a>
          </li>
        
          <li>
            <a href="/2016/06/26/code-management/">代码管理</a>
          </li>
        
          <li>
            <a href="/2016/06/18/violet/">violet - 值得一试的写作同步小助手</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      &copy; 2018 Simon Xu<br>
      Powered by <a href="http://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>
    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/script.js"></script>



  </div>
</body>
</html>